import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
    // 根据当前工作目录中的 `mode` 加载 .env 文件
    const env = loadEnv(mode, process.cwd(), '')

    return {
      base: '/',
        define: {
            __BUILD_TIME__: JSON.stringify(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })),
            'process.env': env
        },
        plugins: [
            vue({
                reactivityTransform: true
            })
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src',
                    import.meta.url))
            }
        },
        server: {
            port: 80,
            host: true,
            open: true,
            cors: true,
            hmr: {
                overlay: true,  // 错误遮罩
                timeout: 5000,  // 热更新超时时间
                clientPort: 80, // 客户端端口
              // host: '0.0.0.0', // 热更新主机
              host: 'localhost', // 热更新主机
            },
            watch: {
                usePolling: true,  // 使用轮询
                interval: 50,      // 轮询间隔
                ignored: [         // 忽略监听的文件
                    '**/node_modules/**',
                    '**/dist/**',
                    '**/.git/**',
                    '**/.env*'
                ]
            },
            proxy: {
                '/api': {
                    target: `http://localhost:${process.env.VITE_APP_API_PORT || 8000}`,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, '')
                }
            }
        },
        build: {
            outDir: 'dist',
            assetsDir: 'assets',
            rollupOptions: {
                output: {
                    manualChunks: undefined
                }
            },
            terserOptions: {
                compress: {
                    drop_console: true,
                    drop_debugger: true,
                },
            },
            brotliSize: false,
            chunkSizeWarningLimit: 2000,
            sourcemap: false,
        },
        optimizeDeps: {
            include: ['vue', 'vue-router', 'pinia', 'axios', 'element-plus'],
            force: true
        },
        css: {
            devSourcemap: true,
        }
    }
})